package com.chhuang.tutool.utils

import java.net.InetAddress
import kotlin.experimental.and

class IPV4Utils {
    companion object{
        private const val TAG = "IPUtils"

        /**
         * 将ip转为int
         * @param ip
         * @return int可能为负数
         * @throws UnknownHostException
         */
        fun ipToInt(ip: String): Int {
            val addr = ipToBytes(ip)
            var address:Int = addr[3].toInt() and 0xFF
            address = address or (addr[2].toInt() shl 8 and 0xFF00)
            address = address or (addr[1].toInt() shl 16 and 0xFF0000)
            address = address or (addr[0].toInt() shl 24 and -0x1000000)
            return address
        }

        /**
         * 将ip转为int
         * @param ip
         * @return xxx.xxx.xxx.xxx
         */
        fun intToIp(ip: Int): String {
            val addr = ByteArray(4)
            addr[0] = (ip ushr 24 and 0xFF).toByte()
            addr[1] = (ip ushr 16 and 0xFF).toByte()
            addr[2] = (ip ushr 8 and 0xFF).toByte()
            addr[3] = (ip and 0xFF).toByte()
            return bytesToIp(addr)
        }

        /**
         * 将byte数组转为ip字符串
         * @param src
         * @return xxx.xxx.xxx.xxx
         */
        fun bytesToIp(src: ByteArray): String {
            return ((src[0] and 0xff.toByte()).toString() + "." + (src[1] and 0xff.toByte()) + "." + (src[2] and 0xff.toByte())
                    + "." + (src[3] and 0xff.toByte()))
        }
        /**
         * 将ip字符串转为byte数组,注意:ip不可以是域名,否则会进行域名解析
         * @param ip
         * @return byte[]
         * @throws UnknownHostException
         */
        fun ipToBytes(ip: String): ByteArray {
            return InetAddress.getByName(ip).address
        }
    }


}